package com.huaxin.hxmoduleworkorder.common.enums.base;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedJdbcTypes(JdbcType.VARCHAR)
public abstract class BaseCodeEnumTypeHandler<T extends Enum<T> & BaseCodeEnum> extends BaseTypeHandler<T> {

    private final Class<T> enumClass;

    protected BaseCodeEnumTypeHandler(Class<T> enumClass) {
        if (enumClass == null) throw new IllegalArgumentException("Enum class cannot be null");
        this.enumClass = enumClass;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, parameter.getCode());
    }

    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String code = rs.getString(columnName);
        return rs.wasNull() ? null : getEnumByCode(code);
    }

    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String code = rs.getString(columnIndex);
        return rs.wasNull() ? null : getEnumByCode(code);
    }

    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String code = cs.getString(columnIndex);
        return cs.wasNull() ? null : getEnumByCode(code);
    }

    private T getEnumByCode(String code) {
        if (code == null) return null;
        for (T t : enumClass.getEnumConstants()) {
            if (t.getCode().equalsIgnoreCase(code)) {
                return t;
            }
        }
        return null;
    }
}